package com.hengxinguotong.zhihuichengjian.ui.building;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.ReplyListAdapter;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.Build;
import com.hengxinguotong.zhihuichengjian.bean.BuildListRes;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.ui.PersonLiableListActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.PullableRecyclerView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/7/11.
 */

public class ReplyListFragment extends BaseFragment implements View.OnClickListener, ReplyListAdapter.OnClickListener{

    private Activity activity;
    private String createBy = null;
    private OnFragmentRemind mListener;

    @BindView(R.id.et_project)
    HXTextView etProject;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;

    private PullableRecyclerView dataRv;

    private ReplyListAdapter replyListAdapter;
    private int pageIndex = 1;
    private List<Build> buildList;
    private String state = "1";//1:待受理; 2:处理中;3:待检查;4:检查不通过；5:已完成
    private int type;
    private String constructionId, userId;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case Constants.LIVE:
                    List<Build> buildDatas = (List<Build>) msg.obj;
                    addBuildData(buildDatas);
                    mListener.getCount();
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getInt("type");
            state = getArguments().getString("state");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_reply_list, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        constructionId = SPUtil.getString(activity, "constructionid");
        userId = SPUtil.getString(activity, "userId");
        initView();
    }

    @Override
    public void onLazyLoad() {
        initData();
    }

    private void initView() {
        switch (type){
            case Constants.LIVE:
                refreshList.setPullUpEnable(false);
                refreshList.setOnPullListener(pullListener);
                dataRv = (PullableRecyclerView) refreshList.getPullableView();
                buildList = new ArrayList<>();
                replyListAdapter = new ReplyListAdapter(getActivity(), buildList);
                replyListAdapter.setOnClickListener(this);
                dataRv.setAdapter(replyListAdapter);

                dataRv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
                break;
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentRemind) {
            mListener = (OnFragmentRemind) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getReplyList("搜索中…");
            }
        }, 500);
    }

    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = buildList.size() / Utils.ONCECOUNT + 1;
            initData();
        }
    };

    public static ReplyListFragment newInstance(int type, String state){
        Bundle bundle = new Bundle();
        bundle.putInt("type",type);
        bundle.putString("state", state);
        ReplyListFragment fragment = new ReplyListFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void setContext(Activity activity) {
        this.activity = activity;
    }

    private void getReplyList(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", constructionId);
            jsonObject.put("pageNum", pageIndex + "");
            jsonObject.put("correctiveStatus", state);
            if (hasList()) {
                jsonObject.put("contactId", userId);
            }
            if(createBy != null){
                jsonObject.put("createBy", createBy);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, activity, "/build/listByConstructionId/" + SPUtil.getString(activity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    BuildListRes res = gson.fromJson(json, BuildListRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = type;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                        if (pageIndex == 1)
                        {
                            refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        } else
                        {
                            refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                        }
                    }
                }else{
                    showToast("系统异常");
                    if (pageIndex == 1)
                    {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    } else
                    {
                        refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
                if (pageIndex == 1)
                {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                } else
                {
                    refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }
        });
    }

    private void addBuildData(List<Build> datas) {
        if (pageIndex == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            buildList = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            buildList.addAll(datas);
        }
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        replyListAdapter.setDataList(buildList);
    }

    @OnClick({ R.id.iv_p, R.id.et_project})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_p:
            case R.id.et_project:
                Intent intent = new Intent(getActivity(), PersonLiableListActivity.class);
                intent.putExtra("type", 0);
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            if(requestCode == 1 && resultCode == 1){
                User user = (User) data.getSerializableExtra("selectUser");
                createBy = user.getUserId();
                etProject.setText(user.getName());
                initData();
            }
            if(requestCode == ReplyListActivity.UPDATE){
                initData();
            }
        }
    }

    @Override
    public void onClick(Object o) {
        Build build = (Build) o;
        if(build == null){
            return;
        }
        Intent intent = new Intent(getActivity(), ReplyActivity.class);
        intent.putExtra("build", build);
        startActivityForResult(intent, ReplyListActivity.UPDATE);
    }
}
